package com.bf.xpdd.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.bf.xpdd.domain.SiteSeller;
import com.bf.xpdd.exception.BaseException;

@Service
@Scope("singleton")
public class AppService 
{
	@Autowired
	private AccountService accountService;
	
	@Autowired
	private TaobaoService taobaoService;
	
	private static boolean isStart = false;
	
	private void keepSessionKeyAlive()
	{
		if(!AppService.isStart)
		{
			Thread thead = new Thread(new Runnable(){

				@Override
				public void run() 
				{
					while(Thread.currentThread().isAlive())
					{
						try 
						{
							List<SiteSeller> sellerList = AppService.this.accountService.findAllSessionKey();
							int len = sellerList.size();
							for(int i = 0; i < len; i++)
							{
								SiteSeller seller = sellerList.get(i);
								//请求超过20分钟以后的才进行维持处理
								if(new Date().getTime() - seller.getTimestamp().getTime() > 20 * 60 * 1000)
								{
									try 
									{
										AppService.this.taobaoService.findUserByNick(sellerList.get(i));
										AppService.this.accountService.updateAccessTime(sellerList.get(i));
									} 
									catch (BaseException e)
									{
										//超出次数限制
										if("27".equals(e.getCode()))
										{
											AppService.this.accountService.removeAllSessionKey();
											Thread.currentThread().sleep(60 * 60 * 1000);
										}
										else if("-1".equals(e.getCode()))
										{
											AppService.this.accountService.removeSessionKey(sellerList.get(i));
										}
									}
								}
								else
								{
									continue;
								}
							}
							Thread.currentThread().sleep(1000);
						} 
						catch (BaseException e) 
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						} 
						catch (InterruptedException e) 
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			});
			thead.setDaemon(true);
			
			thead.start();
			AppService.isStart = true;
		}
	}
	
	public void init()
	{
		this.keepSessionKeyAlive();
	}

}
